import { defineStore } from 'pinia'

// 用户接口类型定义
export interface User {
  userId: string;
  username: string;
  avatar?: string;
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null as User | null,
    token: localStorage.getItem('auth_token') || ''
  }),
  getters: {
    isLoggedIn: (state) => !!state.token && !!state.user,
    userProfile: (state) => state.user
  },
  actions: {
    setUser(user: User) {
      this.user = user
    },
    setToken(token: string) {
      this.token = token
      // 保存到本地存储
      localStorage.setItem('auth_token', token)
    },
    logout() {
      this.user = null
      this.token = ''
      // 清除本地存储
      localStorage.removeItem('auth_token')
    },
    // 从本地存储恢复会话
    initializeAuth() {
      const token = localStorage.getItem('auth_token')
      if (token) {
        this.token = token
        // 这里可以添加获取用户信息的逻辑
      }
    }
  }
})